package com.imooc.api.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 切面类：
 *      打印每个API的执行时间
 */
@Aspect
@Component
@Slf4j
public class ServiceLogAspect {

    @Around("execution(* com.imooc.service.impl..*.*(..))")
    public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {

        long startTime = System.currentTimeMillis();

        Object proceed = joinPoint.proceed();
        String point = joinPoint.getTarget().getClass().getName() + " | " + joinPoint.getSignature().getName();

        long endTime = System.currentTimeMillis();
        long takeTime = endTime - startTime;

        if (takeTime > 1000) {
            log.error("{}执行了{}毫秒", point, takeTime);
        } else if (takeTime > 200) {
            log.warn("{}执行了{}毫秒", point, takeTime);
        } else {
            log.info("{}执行了{}毫秒", point, takeTime);
        }

        return proceed;
    }
}
